<template>
  <div class="app-container">
    <!-- 搜索--------------------------------- -->
    <el-card class="filter-container" shadow="never">
      <div>
        <i class="el-icon-search"></i>
        <span>{{$t('common.filterSearch')}}</span>
        <el-button
          icon="el-icon-search"
          style="float: right"
          @click="fetchData()"
          type="primary"
          size="small"
        >
          {{ $t('common.search') }}
        </el-button>
      </div>
      <div style="margin-top: 15px">
        <el-form :inline="true"  size="small" label-width="140px">
          <el-form-item :label="$t('malllist.search.id')">
            <el-input
              style="width: 203px"
              v-model="searchObj.goodsId"
              :placeholder="$t('malllist.search.plid')"
            />
          </el-form-item>
          <el-form-item :label="$t('malllist.search.name')">
            <el-input
              style="width: 230px margin-left"
              v-model="searchObj.name"
              :placeholder="$t('malllist.search.plname')"
            ></el-input>
          </el-form-item>
           <el-form-item :label="$t('malllist.search.type')">
            <el-input
              style="width: 230px margin-left"
              v-model="searchObj.type"
              :placeholder="$t('malllist.search.pltype')"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <!-- --------------------------------- -->
      <!--导入按钮 -->
    <el-button type="primary" @click="importData">
      <i class="fa fa-plus" />{{ $t('common.import') }}
    </el-button>
     <el-button @click="exportData" type="primary" plain>{{ $t('common.export') }}</el-button>
    <!-- 添加-------------------------------- -->
    <div align="right">
      <el-button type="success" @click="addMall">{{$t('common.add')}}</el-button>
    </div>
    <!-- 批量删除 -->
    <div>
      <el-button type="danger" size="mini" @click="removeRows()"
        >{{ $t('common.bulkDelete') }}</el-button
      >
    </div>
    <!-- --------------------------------------列表页 -->
    <el-table
      :data="list"
      border
      fit
      highlight-current-row
      @sort-change="sortChange"
       @selection-change="handleSelectionChange"
    >
     <el-table-column type="selection" width="55" />
      <el-table-column  :label="$t('malllist.table.goodsId')" width="100" align="center">
        <template slot-scope="scope">
          {{ scope.row.goodsId }}
        </template>
      </el-table-column>

      <el-table-column :label="$t('malllist.table.name')" align="center">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>

      <el-table-column :label="$t('malllist.table.image')" align="center" width="180">
        <template slot-scope="{ row, $index }">
          <img :src="row.image" alt="" style="width: 130px; height: 100px" />
        </template>
      </el-table-column>

      <el-table-column :label="$t('malllist.table.type')" align="center">
        <template slot-scope="scope">
          {{ scope.row.type }}
        </template>
      </el-table-column>

      <el-table-column :label="$t('malllist.table.introduction')" align="center">
        <template slot-scope="scope">
          <span style="text-overflow:ellipsis;overflow:hidden;white-space:nowrap;display:block"  >
          {{ scope.row.introduction }}
          </span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('malllist.table.price')" sortable="custom" prop="price" align="center">
        <template slot-scope="scope">
          {{ scope.row.price }}
        </template>
      </el-table-column>

      <el-table-column :label="$t('malllist.table.salesNumber')" sortable="custom" prop="salesNumber" align="center">
        <template slot-scope="scope">
          {{ scope.row.salesNumber }}
        </template>
      </el-table-column>

      <el-table-column :label="$t('malllist.table.status')" align="center">
        <template slot-scope="scope">
           <el-switch
            v-model="scope.row.status"
            @change="changeSwitch($event, scope.row, scope.$index)"
            active-color="#13ce66"
            :active-value="0"
            :inactive-value="1"
          />
        </template>
      </el-table-column>

      <el-table-column
        :label="$t('common.operate')"
        align="center"
        width="230"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            @click="editMall(scope.row.goodsId)"
          >
            {{ $t('common.update') }}
          </el-button>

          <el-button
            size="mini"
            type="danger"
            @click="delMall(scope.row.goodsId)"
          >
            {{ $t('common.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- --------------------------------------- -->
      <!-- 导入 -->
    <el-dialog title="导入" :visible.sync="dialogImportVisible" width="480px">
      <el-form label-position="right" label-width="170px">
        <el-form-item label="文件">
            <el-upload
              :action="'http://42.194.159.131:8080/mall/batchAddGoods'"
               :headers="headers"
              :on-success="onUploadSuccess"
              :multiple="false"
              class="upload-demo"
              >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传excel文件，且不超过500kb</div>
            </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogImportVisible=false">取消</el-button>
      </div>
    </el-dialog>
    <!-- ----------------------------------分页 -->
    <div class="block" style="float: right; margin-top: 20px">
      <!-- <span class="demonstration">显示总数</span> -->
      <el-pagination
        background
        @current-change="sortChange"
        :current-page.sync="page_num"
        :page-size="page_size"
        layout="total, prev, pager, next"
        :total="total"
      >
      </el-pagination>
    </div>
    <!-- --------------------------------------- -->
  </div>
</template>

<script>
var test=0;
import axios from "axios";
import healmall from "@/api/healthymall";
import { getToken } from "@/utils/auth";
export default {
  data() {
    return {
      orderBy: "12", //排序的方式,是升序还是降序
      key: "", //这个是要排序的字段,需要绑定prop的
      //最后需要把这两个字段传给后端就可以实现排序
      list: [], //列表条件封装对象
      page_num: 1,
      page_size: 8, //每8个数据一页
      total: 1, //初始化
      searchObj: {}, //条件封装对象
      multipleSelection: [], //批量选择中选择的记录列表
      dialogImportVisible:false,//弹框
       headers: {
        Authorization: getToken(),
      },
    };
  },
  created() {
    this.fetchData();
  },
  methods: {
     //导入数据字典
    importData(){
      this.dialogImportVisible = true
    },
     //上传成功调用
    onUploadSuccess(){
        this.dialogImportVisible = false
        this.fetchData(1);
        this.$message({
        	  message: '导入数据成功!',
        	  type: 'success'
          })
    },
     //导出数据字典
    exportData() {
      this.btnLoading = true;
  //  axios({
  //   method: 'get',
  //   url: '/mall/exportGoodsData',
  //   headers: {
  //    Authorization: getToken(),
  //   },
  //   responseType: "blob"
  //  })
  healmall.importmall()
    .then(res => {
    let url = window.URL.createObjectURL(new Blob([this.daochu_data]));
                    let link = document.createElement("a");
                    link.style.display = "none";
                    link.href = url;
                    link.setAttribute("download",  "健康推荐.xls");

                    document.body.appendChild(link);

                    link.click();
    })
    .catch(err => {
     this.btnLoading = false;
     this.$message.error("下载失败");
    });
    },
    //修改商品上架下架状态
    changeSwitch(e, row, index) {
      console.log(e, row, index);
      let uid = row.goodsId;
      let type = row.status;
      console.log("aaaaaaaaaa", uid);
      console.log("qqqqqqqqqq", type);
      healmall
        .salestatus(uid, type)
        .then((res) => {
          console.log("zsjzsj", res);
          this.$message({
            type: "success",
            message: type==0?"商品上架成功!":"商品下架成功!",
          });
          if(test=1)
          this.sortChange();
          else if(test =0)
          this.fetchData(uid ? this.page_num : 1);
        })
        .catch(() => {
          // this.$message({
          //   type: "info",
          //   message: "已取消删除",
          // });
        });
    },
     //获取选择复选框的id值
    handleSelectionChange(selection) {
      this.multipleSelection = selection;
    },
     //批量删除
    removeRows() {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //遍历数组得到每个id值，设置到idList里面
          var idList = [];
          for (var i = 0; i < this.multipleSelection.length; i++) {
            var obj = this.multipleSelection[i];
            var id = obj.goodsId;
            idList.push(id);
          }
          //调用接口
          healmall.batchRemoveMall(idList).then((resp) => {
            //提示
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            //刷新页面数据
            this.fetchData(1);
          })
          .catch(()=>{
          
          this.$message({
            type: "error",
            message: "删除失败!权限不足，请联系管理员进行升级",
          });
        
       })
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //价格升序或者降序
    sortChange(column) {
      test=1
      var vm = this;
      this.key = column.prop;
      // console.log("aaaaaaaaaa", column);
      // this.orderBy=12
      if (this.key == "price" && column.order == "ascending") {
        this.orderBy = "0";
      } else if (this.key == "price" && column.order == "descending") {
        this.orderBy = "1";
      } else if (this.key == "salesNumber" && column.order == "ascending") {
        this.orderBy = "2";
      } else if (this.key == "salesNumber" && column.order == "descending") {
        this.orderBy = "3";
      }
      console.log("qqqqqqqq", this.orderBy);
      console.log("qqqqqqqq", this.key);
      healmall
        .priceOrsaleNum(this.page_num, this.page_size, this.orderBy)
        .then((res) => {
          console.log(this.orderBy);
          console.log("zsjzsj", res.data.Goods.list);
          vm.list = res.data.Goods.list;
          vm.total = res.data.Goods.total;
          // this.fetchData();
        });
    },
    //添加商品
    addMall() {
      this.$router.push("/HealthyMall/addmall");
    },
    //修改商品
    editMall(goodsId) {
      this.$router.push("/HealthyMall/editmall/" + goodsId);
    },
    //页面列表页渲染，请求接口调用
    fetchData(page = 1) {
      this.page_num = page;
      var vm = this;
      healmall
        .getHealthymallList(this.page_num, this.page_size, this.searchObj)
        //请求成功调用
        .then((resp) => {
          vm.list = resp.data.Goods.list;
          vm.total = resp.data.Goods.total;
          console.log(vm.total);
          console.log('aaaa',vm.list);
          if (
            this.searchObj.goodsId == this.list[0].goodsId ||
            this.searchObj.type == this.list[0].type
          ) {
            this.$message({
              type: "success",
              message: "搜索成功!",
            });
          }
        })
        .catch((error) => {});
    },
    // 删除方法------------------
    delMall(goodsId) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //调用接口
          healmall.delmall(goodsId).then((resp) => {
            //提示
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            //刷新页面数据
            this.fetchData(1);
          })
          .catch(()=>{
          
          this.$message({
            type: "error",
            message: "删除失败!权限不足，请联系管理员进行升级",
          });
        
       })
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // --------------------------------------------
  },
};
</script>
